package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.common.RedisConst;
import com.itheima.health.dao.SetMealDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import okio.BufferedSink;
import org.apache.zookeeper.server.ExitCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangmeng
 * @description 套餐SEVICE实现类
 * @date 2019/9/26
 **/
@Service(interfaceClass = SetMealService.class)
@Slf4j
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private SetMealDao setMealDao;
    @Transactional
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        log.info("[套餐-添加]setmeal:{},checkgroupIds:{}",setmeal,checkgroupIds);
        // 调用DAO数据入库
        // 插入基本数据
        setMealDao.insert(setmeal);
        log.info("[套餐-向MySQL插入基本数据]");

        // 向Redis中插入基本数据
        try(Jedis jedis = jedisPool.getResource()) {
            String field = RedisConst.SETMEAL_LIST_PREFIX + setmeal.getId();
            log.info("[套餐-向Redis中插入基本数据]key:{}",field);


            String setmealJsonString = JSON.toJSONString(setmeal);
            log.info("[套餐-向Redis中插入基本数据]setmealParseJson:{}", setmealJsonString);


            Long hset = jedis.hset(RedisConst.SETMEAL_LIST_HASH, field, setmealJsonString);
            log.info("[套餐-向Redis中插入基本数据]hset(插入成功返回1):{}",hset);
        }

        // 插入关联数据
        for (Integer checkgroupId : checkgroupIds) {
            log.info("[套餐-向MySQL插入关联数据]checkgroupId:{}",checkgroupId);
            setMealDao.insertSetMealAndCheckGroup(setmeal.getId(),checkgroupId);
        }
        //图片不为空，则操作redis进行记录
        if(!StringUtils.isEmpty(setmeal.getImg())) {
            try (Jedis jedis = jedisPool.getResource()) {
                jedis.sadd(RedisConst.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //设置分页参数
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //DAO查询数据
        Page<Setmeal> page = setMealDao.selectByCondition(queryPageBean.getQueryString());
        //封装返回值
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Setmeal> findAll() {

        // 1. 是否在Redis中可以找到
        // 查询出数据并返回
        try(Jedis jedis = jedisPool.getResource()) {
            if (jedis.exists(RedisConst.SETMEAL_LIST_HASH)) {
                List<String> rowJsonList = jedis.hvals(RedisConst.SETMEAL_LIST_HASH);
                log.info("[套餐-在Redis中查询所有]rowJsonList:{}",rowJsonList);
                List<Setmeal> setmealParseJson = new ArrayList<>();

                for (String rowJson : rowJsonList) {
                    setmealParseJson.add(JSON.parseObject(rowJson, Setmeal.class));
                }
                log.info("套餐-在Redis中查询所有]setmealParseJson:{}",setmealParseJson);

                return setmealParseJson;
            }
        }

        //调用DAO查询所有
        log.info("套餐-在MySQL中查询所有]");
        return setMealDao.selectAll();
    }

    @Override
    public Setmeal findById(Integer id) {
        // 1. 判空
        if (null == id) {
            return null;
        }

        // 2. 是否在Redis中可以找到
        // 查询出数据并返回
           try(Jedis jedis = jedisPool.getResource()) {
               String field = RedisConst.SETMEAL_LIST_PREFIX + id;
               log.info("[套餐-根据ID在Redis中查找]key:{}",field);

               if (jedis.hexists(RedisConst.SETMEAL_LIST_HASH, field)) {
                   String rowJson = jedis.hget(RedisConst.SETMEAL_LIST_HASH,field);
                   log.info("[套餐-根据ID在Redis中查找]rowJson:{}",rowJson);

                   Setmeal setmealParseJson = JSON.parseObject(rowJson, Setmeal.class);
                   log.info("[套餐-根据ID在Redis中查找]setmealParseJson:{}",setmealParseJson);

                   return setmealParseJson;
               }
           }

        // 3. 在MySQL中可以找到, 如果找到, 加入Redis并返回
        Setmeal setmealFromMySQL = setMealDao.selectById(id);
        if (null != setmealFromMySQL) {
            try(Jedis jedis = jedisPool.getResource()) {
                String key = RedisConst.SETMEAL_LIST_PREFIX + setmealFromMySQL.getId();
                log.info("[套餐-根据ID在MySQL中查找-新生成Redis的key]key:{}",key);

                String jsonString = JSON.toJSONString(setmealFromMySQL);
                log.info("[套餐-根据ID在MySQL中查找]jsonString:{}",jsonString);

                Long hset = jedis.hset(RedisConst.SETMEAL_LIST_HASH, key, jsonString);
                log.info("[套餐-根据ID在MySQL中查找]1视为成功:{}",hset);
            }
        }

        //调用DAO查询数据
        return setmealFromMySQL;
    }
}
